using BootstrapBlazor.Components;

using Furion;
using Furion.VirtualFileServer;


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using SqlSugar;
using System.Linq;
using System;
using Application.Service.Auth;
using Application.Service.LogCache;
using Application.Web.Core.Services;
using Application.Service;
using Application.Service.Permissions;

namespace Application.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            services.AddControllers().AddInjectWithUnifyResult();
            services.AddRazorPages();
			services.AddRazorComponents().AddInteractiveServerComponents();
            services.AddServerSideBlazor();
            services.AddBootstrapBlazor(options =>
            {
                // 统一设置 Toast 组件自动消失时间
                options.ToastDelay = App.GetConfig<int>("BootstrapBlazorOptions:ToastDelay");
            });

			// 增加 Table Excel 导出服务
			services.AddBootstrapBlazorTableExportService();
			
            // 添加前端锁屏服务
            services.AddScoped<LockScreen>();

			// 添加前端检查权限服务
			services.AddScoped<CheckPermission>();

			// 注册 SQLSugar（Sqlite）并规范化 Data Source 路径
			services.AddSingleton<ISqlSugarClient>(sp =>
			{
				var env = sp.GetRequiredService<IHostEnvironment>();

                // 从 appsettings.json 读取 connection 节点内容
                var conn = App.GetConfig<string>("ConnectionConfigs:ConnectionString");// builder.Configuration["connection"];

				var normalized = DbService.NormalizeSqliteConnectionString(conn, env.ContentRootPath);

				return new SqlSugarScope(new ConnectionConfig
				{
					ConnectionString = normalized,
					DbType = DbType.Sqlite,
					IsAutoCloseConnection = true,
					InitKeyType = InitKeyType.Attribute
				},
				db =>
				{
					// 可选：SQL 输出
					db.Aop.OnLogExecuting = (sql, pars) =>
					{
						System.Console.WriteLine(UtilMethods.GetSqlString(DbType.Sqlite, sql, pars));
					};
				});
			});
		}

		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
			// 启动时初始化表结构
			using (var scope = app.ApplicationServices.CreateScope())
			{
				var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
				// 创建数据库（Sqlite）若不存在
				var created = DbService.CreateDBFile(db);
				// 如需按实体自动建表，取消注释并替换为实际实体类型：
				// DbContext.Instance.CodeFirst.InitTables(typeof(YourEntity1), typeof(YourEntity2));

				// 反射扫描所有带有 [SugarTable] 特性的实体类型
				var modelTypes = AppDomain.CurrentDomain.GetAssemblies()
					.Where(a => !a.IsDynamic
						&& !a.FullName.StartsWith("System.", StringComparison.OrdinalIgnoreCase)
						&& !a.FullName.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase)
						&& !a.FullName.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase))
					.SelectMany(a =>
					{
						try { return a.GetExportedTypes(); }
						catch { return Type.EmptyTypes; }
					})
					.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttributes(typeof(SugarTable), inherit: true).Any())
					.ToArray();

				// 根据实体类型创建表（存在则不创建）
				if (modelTypes.Length > 0)
				{
					db.CodeFirst.InitTables(modelTypes);
				}
				if (created == 1)
				{
					//新增User、Permission、UserPermission种子数据
					DbService.SeedDataCommit(db);
				}
			}

			if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
			app.UseAntiforgery();
			
			app.UseUnifyResultStatusCodes();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}
